package giab.weixin.web.httpservice;

import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

@Component 
public class HttpBaseService {
	private static final String urlPrefix="http://218.240.38.167:8080/rz/mobile/";
	public String postUrlResult(String url, List<NameValuePair> postParam) {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(urlPrefix+url);
		httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
		try {
			httppost.setEntity(new UrlEncodedFormEntity(postParam, HTTP.UTF_8));
			HttpResponse response = httpClient.execute(httppost);
			String strResult = EntityUtils.toString(response.getEntity());
			if (strResult != null) {
				return strResult;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return "";
	}

	public String getUrlResult(String url,List<NameValuePair> getParam) {
		String get = getParam(getParam);
		if(get.length()>0){
			url+="/?"+get;
		}
		HttpGet httpRequest = new HttpGet(urlPrefix+url);
		try {
			HttpResponse httpResponse = new DefaultHttpClient()
					.execute(httpRequest);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				/* 取出响应字符串 */
				String strResult = EntityUtils.toString(httpResponse
						.getEntity());
				if (strResult != null) {
					return strResult;
				}

			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return "";
	}
	private String getParam(List<NameValuePair> getParam){
		String str ="";
		for (NameValuePair nameValuePair : getParam) {
			if(str.length()>0){
				str+="&";
			}
			str+=nameValuePair.getName()+"="+nameValuePair.getValue();
		}
		return str;
	}

}
